package com.wswy.wzcx.ui.persenter;

import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.che.libcommon.api.BaseResult;
import com.che.libcommon.api.ProgressDialogObserver;
import com.che.libcommon.utils.RxBus;
import com.che.libcommon.utils.optional.Optional;
import com.wswy.wzcx.R;
import com.wswy.wzcx.api.Api;
import com.wswy.wzcx.api.ErrorCode;
import com.wswy.wzcx.model.BookMode;
import com.wswy.wzcx.model.Genre;
import com.wswy.wzcx.model.GenreWare;
import com.wswy.wzcx.model.UserMode;
import com.wswy.wzcx.module.InternalMsgCode;
import com.wswy.wzcx.module.core.BasePresenter;
import com.wswy.wzcx.ui.view.BookKeepView;
import com.wswy.wzcx.utils.StatusBarCompat;

import com.wswy.wzcx.utils.UiUtils;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Function;
import io.reactivex.observers.ResourceObserver;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;

/**
 * Created by wangduheng26 on 2018/2/5.
 * wangduheng26@gmail.com
 */

public class BookKeepPresenter extends BasePresenter{

    private static final String TAG = "BookKeepPresenter";

    private BookKeepView mView;

    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        disposables = new CompositeDisposable();
        ResourceObserver<List> observer = new ResourceObserver<List>() {
            @Override
            public void onNext(List genres) {
                mView.onSuccess(genres);
            }

            @Override
            public void onError(Throwable e) {
                mView.onSuccess(null);
            }

            @Override
            public void onComplete() {

            }
        };
        RxBus.getDefault()
                .toObservableWithCode(InternalMsgCode.CODE_BOOK_KEEP_CHANGE, List.class)
                .subscribeWith(observer);
        disposables.add(observer);

    }


    public BookKeepPresenter(BookKeepView view) {
        this.mView = view;
    }

    public void setup() {
        ProgressDialogObserver<List<Genre>> observer = new ProgressDialogObserver<List<Genre>>(mView.activity(), "提示", "正在加载数据...") {
            @Override
            protected void onApiResult(@Nullable List<Genre> genres) {
                RxBus.getDefault().postWithCode(InternalMsgCode.CODE_BOOK_KEEP_CHANGE, genres);
            }

            @Override
            protected void onApiError(@Nullable BaseResult result) {
                if(result!=null&&(ErrorCode.isTokenInvalid(result.statusCode))){
                    showLoginView();
                }else{
                    toastErrorMsg(result);
                }
            }
        };
        Api.get().fetchBillList()
                .map(getConvert())
                .subscribe(observer);

    }

    private void showLoginView() {
        mView.showLoginView();
    }

    private Function<Optional<BookMode>, Optional<List<Genre>>> getConvert() {
        return new Function<Optional<BookMode>, Optional<List<Genre>>>() {
            @Override
            public Optional<List<Genre>> apply(Optional<BookMode> optional) throws Exception {
                BookMode bookMode = optional.orNull();
                List<Genre> res = new ArrayList<>();
                if (bookMode != null) {
                    mView.setTopString(bookMode.currentMonthAmount);
                    List<GenreWare> wares = bookMode.list;
                    if (wares != null) {
                        for (GenreWare ware : wares) {
                            Genre genre = new Genre(ware);
                            res.add(genre);
                        }
                    }
                } else {
                    mView.setTopString("");
                }

                return Optional.of(res);
            }
        };
    }

    @Override
    protected void onUserLoginSuccess(UserMode userMode) {
        super.onUserLoginSuccess(userMode);
        mView.hideLoginView();
        setup();
    }

    @Override
    protected void onLogout() {
        super.onLogout();
        mView.showLoginView();
    }

    public void setUpStatusBar(View inflate) {
        if (inflate == null) return;
        if (StatusBarCompat.isM()) {
            Context context = inflate.getContext();
            Resources resources = context.getResources();
            StatusBarCompat.init(inflate.getContext());
            final int statusBarHeight = StatusBarCompat.STATUS_BAR_HEIGHT;
            int height = 0;

//

            LinearLayout layout = inflate.findViewById(R.id.header_bar);
            final int layoutHeight = resources.getDimensionPixelSize(R.dimen.header_bar_content_height) + statusBarHeight;
            height += layoutHeight;
            layout.getLayoutParams().height=layoutHeight;
            StatusBarCompat.setup(layout);

            View btn = inflate.findViewById(R.id.btn_add);
            ViewGroup.LayoutParams layoutParams1 = btn.getLayoutParams();
            if (layoutParams1 instanceof ViewGroup.MarginLayoutParams) {
                int bottomMargin = ((ViewGroup.MarginLayoutParams) layoutParams1).bottomMargin;
                height += (resources.getDimensionPixelSize(R.dimen.header_bar_btn_height)/2  + bottomMargin );
                FrameLayout frameLayout = inflate.findViewById(R.id.header);
                frameLayout.getLayoutParams().height = height ;
            }


            //计算让字居中显示
            final View llShow = inflate.findViewById(R.id.ll_show);
            UiUtils.INSTANCE.addOnGlobalLayoutListener(llShow, new Function1<View, Unit>() {
                @Override
                public Unit invoke(View view) {

                    ViewGroup.LayoutParams layoutParams = llShow.getLayoutParams();
                    if(layoutParams instanceof ViewGroup.MarginLayoutParams){
                        ((ViewGroup.MarginLayoutParams) layoutParams).topMargin= (layoutHeight-statusBarHeight-llShow.getHeight())/2;
                    }

                    return null;
                }
            });

//            TextView textView = inflate.findViewById(R.id.tv_show_top);
//            ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
//            if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
//                ((ViewGroup.MarginLayoutParams) layoutParams).topMargin += statusBarHeight;
//            }
        }


    }
}
